<?php


namespace models\Business\Tbk;


use models\Exception\Business\TbkcategoryException;
use models\Exception\DAO\ModelDriverException;
use models\Exception\DAO\ModelException;
use models\Exception\DAO\ModelReflectionException;
use models\Exception\DAO\ModelSqlException;
use models\Exception\Service\ServiceException;
use models\Exception\Transformer\TransformerException;
use models\Service\TbkcategoryService;
use models\Service\UserService;
use Yaf\Registry;

class TbkCategory
{
    /**
     * 获取淘宝客商品分类列表
     * @param array $parameters
     * @return array|mixed
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TbkcategoryException
     * @throws TransformerException
     */
    static public function getTbkCategoryList($parameters = []) {
        try {
            $rules = $condition = [];

            if (isset($parameters['id']))
                array_push($rules, ['field' => 'id', 'op' => 'eq', 'data' => $parameters['id']]);

            if (isset($parameters['stats'])) {
                if ($parameters['stats'] == '999' && isset($parameters['from_api']) && $parameters['from_api'] === true)
                    array_push($rules, ['field' => 'stats', 'op' => 'eq', 'data' => 1]);
                else
                    array_push($rules, ['field' => 'stats', 'op' => 'eq', 'data' => $parameters['stats']]);
            }

            if (isset($parameters['name']))
                array_push($rules, ['field' => 'name', 'op' => 'nc', 'data' => '%' . $parameters['name'] . '%']);

            if (!empty($rules))
                $condition = ['groupOp' => 'AND', 'rules' =>  $rules];

            $category_list = TbkcategoryService::getInstance()->getList(
                isset($parameters['page']) ? $parameters['page'] : 1,
                isset($parameters['page_size']) ? $parameters['page_size'] : 10,
                isset($parameters['sort']) ? $parameters['sort'] : 'desc',
                isset($parameters['order']) ? $parameters['order'] : 'id',
                $condition
            );

            if (empty($category_list['data']))
                throw new TbkcategoryException(TbkcategoryException::TBKCATEGORY_IS_NOT_EXISTS, TbkcategoryException::TBKCATEGORY_IS_NOT_EXISTS_NO);

            foreach ($category_list['data'] as $idx => $category_info) {
                $icon = $category_info['icon'];
                if (!empty($icon)) {
                    if (strpos($icon, 'http://') === false || strpos($icon, 'https://') === false)
                        $icon = Registry::get('config')['application']['host'] . $category_info['icon'];
                }
                $category_list['data'][$idx]['icon'] = $icon;
            }

            return $category_list;
        } catch (TbkcategoryException $e) {
            throw $e;
        } catch (ModelDriverException $e) {
            if ($e->getCode() == ModelDriverException::DRIVER_EXCEPTION_MSG_NO)
                throw new TbkcategoryException(TbkcategoryException::TBKCATEGORY_IS_NOT_EXISTS, TbkcategoryException::TBKCATEGORY_IS_NOT_EXISTS_NO);
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }
    }

    static public function editTbkCategory($parameters = []) {
        try {
            if (!isset($parameters['id']) || empty($parameters['id']))
                throw new TbkcategoryException(TbkcategoryException::TBKCATEGORY_ID_IS_EMPTY, TbkcategoryException::TBKCATEGORY_ID_IS_EMPTY_NO);

            $update_arr = [];
            if (isset($parameters['stats']))
                $update_arr['stats'] = $parameters['stats'];

            if (isset($parameters['name']))
                $update_arr['name'] = $parameters['name'];

            if (isset($parameters['icon']))
                $update_arr['icon'] = str_replace(Registry::get('config')['application']['host'], '', $parameters['icon']);

            if (!empty($update_arr)) {
                $tbk_category_info = TbkcategoryService::getInstance()->update($update_arr, $parameters['id']);
            } else
                $tbk_category_info = TbkcategoryService::getInstance()->getOne($parameters['id']);

            return $tbk_category_info;
        } catch (TbkcategoryException $e) {
            throw $e;
        } catch (ModelDriverException $e) {
            if ($e->getCode() == ModelDriverException::DRIVER_EXCEPTION_MSG_NO)
                throw new TbkcategoryException(TbkcategoryException::TBKCATEGORY_EDIT_FAILURE, TbkcategoryException::TBKCATEGORY_EDIT_FAILURE_NO);
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }
    }

    /**
     * 淘宝客商品列表获取对应的分类名
     * @param array $module_list
     * @return array
     */
    static public function getCategoriesByModules($module_list = []) {
        try {
            $category_name_arr = [];
            $category_id_arr = array_column($module_list['data'], 'category_id');

            $category_id_arr = array_values(array_filter(array_unique($category_id_arr)));

            $category_list = [];
            if (count($category_id_arr) == 1)
                $category_list['data'][] = TbkcategoryService::getInstance()->getOne(implode(',', $category_id_arr));
            else if (count($category_id_arr) > 1)
                $category_list = TbkcategoryService::getInstance()->getList(1, count($category_id_arr), 'desc', 'id',
                    ['groupOp' => 'AND',
                        'rules' => [['field' => 'id', 'op' => 'in', 'data' => implode(',', $category_id_arr)]]]);

            $category_name_arr = array_column($category_list['data'], 'name', 'id');
        } catch (\Exception $e) {

        } finally {
            foreach ($module_list['data'] as $idx => $info) {
                if (isset($info['category_id'])) {
                    $module_list['data'][$idx]['category_name'] = isset($category_name_arr[$info['category_id']]) ?
                        $category_name_arr[$info['category_id']] : '';
                }
            }

            return $module_list;
        }

    }

}
